﻿using MediatR;
using RearLivestock.Common.Domains.Enum;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using static NPOI.HSSF.Util.HSSFColor;

namespace RearLivestock.Beginning.Api.Application.Command.PigArchives
{
    /// <summary>
    /// 获取猪只档案详情
    /// </summary>
    public class DetailsPigfileHandler : IRequestHandler<DetailsPigfileCommand, Result>
    {
        /// <summary>
        /// 猪只档案仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> _basicInformationRepository;

        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> _bedroomsRepository;

        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> _fieldsRepository;

        /// <summary>
        /// 猪只类型仓储
        /// </summary>
        private readonly IBaseRepository<PigType> _pigTypeRepository;

        /// <summary>
        /// 品种仓储
        /// </summary>
        private readonly IBaseRepository<Varieties> _varietiesRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DetailsPigfileHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="basicInformationRepository"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="fieldsRepository"></param>
        /// <param name="pigTypeRepository"></param>
        /// <param name="varietiesRepository"></param>
        /// <param name="logger"></param>
        public DetailsPigfileHandler(IBaseRepository<BasicInformation> basicInformationRepository,
                                     IBaseRepository<Bedrooms> bedroomsRepository,
                                     IBaseRepository<Fields> fieldsRepository,
                                     IBaseRepository<PigType> pigTypeRepository,
                                     IBaseRepository<Varieties> varietiesRepository,
                                     ILogger<DetailsPigfileHandler> logger)
        {
            _basicInformationRepository = basicInformationRepository;
            _bedroomsRepository = bedroomsRepository;
            _fieldsRepository = fieldsRepository;
            _pigTypeRepository = pigTypeRepository;
            _varietiesRepository = varietiesRepository;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DetailsPigfileCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = (from a in await _basicInformationRepository.GetAll()
                             join b in await _bedroomsRepository.GetAll() on a.BedroomId equals b.BedroomId into bedrooms
                             from bed in bedrooms.DefaultIfEmpty()// 左连接，即使没有匹配的BedroomId也能返回结果
                             join c in await _fieldsRepository.GetAll() on a.FieldId equals c.FieldId into fields
                             from fld in fields.DefaultIfEmpty() // 左连接，即使没有匹配的FieldId也能返回结果
                             join d in await _pigTypeRepository.GetAll() on a.PigTypeId equals d.PigTypeId
                             join e in await _varietiesRepository.GetAll() on a.VarietiesId equals e.VarietiesId
                             where a.BasicInforId == request.BasicInforId
                             select new PigfileDetailsDto()
                             {
                                 BasicInforId = a.BasicInforId,
                                 EarNumber = a.EarNumber,
                                 Electronicearlabel = a.Electronicearlabel,
                                 GeneticlevelEnums = a.GeneticlevelEnums,
                                 Gender = a.Gender,
                                 VarietiesId = a.VarietiesId,
                                 FatherEarNumber = a.FatherEarNumber,
                                 MotherEarNumber = a.MotherEarNumber,
                                 BirthDate = a.BirthDate,
                                 EntryDate = a.EntryDate,
                                 Birthplace = a.Birthplace,
                                 BirthWeight = a.BirthWeight,
                                 Remarks = a.Remarks,
                                 BirthStatus = a.BirthStatus,
                                 PigTypeId = a.PigTypeId,
                                 BedroomId = a.BedroomId,
                                 FieldId = a.FieldId,
                                 Presentstatus = a.Presentstatus,
                                 Reproductivestatus = a.Reproductivestatus,
                                 Productiongrade = a.Productiongrade,
                                 Saleslevel = a.Saleslevel,
                                 IsPrenatalCheckup = a.IsPrenatalCheckup,
                                 CreatedOwner = a.CreatedOwner,
                                 CreatedTime = a.CreatedTime,
                                 UpdateOwner = a.UpdateOwner,
                                 UpdateTime = a.UpdateTime,
                                 ExamineOwner = a.ExamineOwner,
                                 ExamineTime = a.ExamineTime,
                                 BedroomName = bed.BedroomName ?? "未知",
                                 FieldName = fld.FieldName ?? "未知",
                                 PigTypeName = d.PigTypeName,
                                 VarietiesName = e.VarietiesName,
                             }).FirstOrDefault();
                result.Code = (int)CommonErrorCode.Success;
                result.Data = query;
                result.Msg = "获取猪只详情成功";
            }
            catch (Exception ex)
            {
                result.Msg = "获取猪只详情异常" + ex.Message;
                _logger.LogError("获取猪只详情异常" + ex.Message);
            }
            return result;
        }
    }
}
